import React from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd';
import styles from './login.module.scss'
import src from '../../assets/logo.png'
import { useDispatch } from 'react-redux';
import { login } from '@/store/actions/login.js'
import { useHistory,useLocation } from 'react-router-dom';
export const Login = () => {
  const history=useHistory()
  const dispatch = useDispatch()
  const location=useLocation()
  //表单验证通过后执行的函数
  const onFinish = async(values) => {
    try {
      await dispatch(login(values.mobile, values.code))
      //从location中取到传入的值,判断是否有值
    history.replace(location.state?location.state.from:'/home')
    } catch (error) {
      message.warn('登录失败')
    }
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (
    <div className={styles.root}>
      <Card className='card' bordered={false}  style={{ width: 400 }}  bodyStyle={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}>
        <img className='logo' src={src} alt='' />
        {/* 表单 */}
        <Form
      validateTrigger='onBlur'
      name="basic"
      initialValues={{
        remember: true,
        mobile: '13911111111',
        code:'246810'
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
          autoComplete="off"
    >
      <Form.Item
        name="mobile"
        rules={[
          {
            required: true,
            message: '请输入手机号!',
          },
          {
            pattern: /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/,
            message: '请输入正确的手机号!',
          },
        ]}
      >
        <Input placeholder='请输入手机号'/>
      </Form.Item>

      <Form.Item
        name="code"
        rules={[
          {
            required: true,
            message: '请输入验证码!',
          },
          {
            len: 6,
            message: '验证码需6位数',
          },
          {
            pattern: /^[0-9]*$/,
            message: '验证码需要数字!',
          },
        ]}
      >
        <Input placeholder='请输入验证码'/>
      </Form.Item>

      <Form.Item
        name="remember"
        valuePropName="checked"
      >
        <Checkbox style={{color:'#1890ff'}}>我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" style={{width:'100%'}}>
          Submit
        </Button>
      </Form.Item>
    </Form>
      </Card>
    </div>
  )
}
